package org.awa.demo.opencv.service.impl;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.awa.demo.opencv.demo.FaceDetection;
import org.awa.demo.opencv.entity.SoundBuildColRelationEntity;
import org.awa.demo.opencv.entity.SoundBuildRowRelationEntity;
import org.awa.demo.opencv.entity.SoundCalBuildLogEntity;
import org.awa.demo.opencv.entity.SoundCalLogEntity;
import org.awa.demo.opencv.gis.bean.BuildingOrder;
import org.awa.demo.opencv.gis.bean.Element;
import org.awa.demo.opencv.mapper.SoundBuildColRelationMapper;
import org.awa.demo.opencv.mapper.SoundBuildRowRelationMapper;
import org.awa.demo.opencv.mapper.SoundCalBuildLogMapper;
import org.awa.demo.opencv.service.IOpenCvService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Calendar;

/**
 * @author xxf
 */
@Slf4j
@Service
public class OpenCvServiceImpl implements IOpenCvService {

    @Resource
    private SoundCalBuildLogMapper soundCalBuildLogMapper;

    @Resource
    private SoundBuildRowRelationMapper soundBuildRowRelationMapper;

    @Resource
    private SoundBuildColRelationMapper soundBuildColRelationMapper;

    @Override
    public boolean hasFace(MultipartFile file) throws Exception{
        String fileName = file.getOriginalFilename();
        int index = fileName.lastIndexOf(".");
        String ext = fileName.substring(index+1);
        String outFileName = fileName.substring(0,index) + "_face."+ext;
        return FaceDetection.testModel(FaceDetection.createMat(getByteFromFile(file)),outFileName) > 0;
    }

    private byte[] getByteFromFile(MultipartFile file) throws Exception{
        byte[] buffer = null;
        ByteArrayOutputStream bos = null;
        BufferedInputStream fis = null;

        try {
            fis = new BufferedInputStream(file.getInputStream());
            bos = new ByteArrayOutputStream();

            byte[] b = new byte[2048];

            int n;

            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }

            buffer = bos.toByteArray();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (null != bos) {
                    bos.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally{
                try {
                    if(null!=fis){
                        fis.close();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }

        return buffer;
    }

    /**
     * 根据二维网格生成图片
     *
     * @param buildingOrder
     * @throws Exception
     * @return
     */
    @Override
    public SoundCalBuildLogEntity buildImageFromSoundArr(SoundCalLogEntity calLog, BuildingOrder buildingOrder) throws Exception{
        Element[][] elements = buildingOrder.getElements();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR,-1);
        String path = "buildImage_"+buildingOrder.getGeoId()+"_"+ DateUtil.format(calendar.getTime(),"yyyyMMddHH") + ".png";
        if(FaceDetection.transAndSaveImage(elements,buildingOrder.getLength(),buildingOrder.getHeight(),path)){
            return saveBuildLogToDb(calLog,buildingOrder,path);
        }
        return null;
    }

    private SoundCalBuildLogEntity saveBuildLogToDb(SoundCalLogEntity calLog,BuildingOrder buildingOrder,String path){
        SoundCalBuildLogEntity calBuildLog = new SoundCalBuildLogEntity();
        calBuildLog.setCalId(calLog.getId());
        calBuildLog.setBuildId(buildingOrder.getBuildId());
        calBuildLog.setDateTime(calLog.getDateTime());
        calBuildLog.setGeoId(buildingOrder.getGeoId());
        calBuildLog.setGeom(buildingOrder.getTheGeom());
        calBuildLog.setHeight(buildingOrder.getHeight());
        calBuildLog.setLength(buildingOrder.getLength());
        calBuildLog.setName(buildingOrder.getName());
        calBuildLog.setPathUrl(path);
        soundCalBuildLogMapper.insert(calBuildLog);

//        Element[][] elements = buildingOrder.getElements();
//        for (int i = 0; i < elements.length; i++) {
//            Element[] elementRow = elements[i];
//            if(elementRow.length == 0){
//                continue;
//            }
//            SoundBuildRowRelationEntity rowEntity = new SoundBuildRowRelationEntity();
//            rowEntity.setCalBuildId(calBuildLog.getBuildId());
//            rowEntity.setCalId(calLog.getId());
//            rowEntity.setHeight(elementRow[0].getHeight());
//            soundBuildRowRelationMapper.insert(rowEntity);
//
//            for (int j = 0; j < elementRow.length; j++) {
//                Element elementCol = elementRow[j];
//                SoundBuildColRelationEntity colEntity = new SoundBuildColRelationEntity();
//                colEntity.setLeqt(elementCol.getLeqt());
//                colEntity.setCalId(calLog.getId());
//                colEntity.setCalRowId(rowEntity.getId());
//                colEntity.setSort(j);
//                colEntity.setLeqt(BigDecimal.valueOf(elementCol.getLeqt()).setScale(1, RoundingMode.HALF_EVEN).doubleValue());
//                colEntity.setX(BigDecimal.valueOf(elementCol.getX()).toString());
//                colEntity.setY(BigDecimal.valueOf(elementCol.getY()).toString());
//                log.info(">>>>> "+colEntity);
//                soundBuildColRelationMapper.insert(colEntity);
//            }
//        }

        return calBuildLog;
    }
}
